package com.kongming.kmdm.ws.rest.actor;

import akka.actor.UntypedActor;
import com.kongming.kmdm.ws.list.WSList;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.Session;
import java.util.Map;

public class PushMsgActor extends UntypedActor {

    private static Map<String, WSList> ssnMap;

    private static Logger logger = LoggerFactory.getLogger(PushMsgActor.class);

    //private IRedisCache                         cache;

    //private WSConfig                            config;

    @SuppressWarnings("static-access")
    public PushMsgActor(Map<String, WSList> ssnMap) {

        //config = new WSConfig ();
        //cache = new RedisStorage (config.getRedisURl ());
        this.ssnMap = ssnMap;
    }

//    @Override
    public void onReceive(Object arg0) throws Exception {

        logger.info("rsv msg:----" + arg0);
        JSONObject jsonData = JSONObject.fromObject(arg0);
        String pushId = jsonData.getString("pushId");
        JSONObject rstJson = jsonData.getJSONObject("msg");

        logger.info("ssnMapHashcode {}", ssnMap.hashCode());
        //将消息push到redis中
        //cache.set (config.getRedisMsgKey () + pushId, rstJson.toString ());
        if (ssnMap.containsKey(pushId)) {
            WSList sessionList = ssnMap.get(pushId);
            for (Session sess : sessionList.getClone()) {
                if (sess != null && sess.isOpen()) {
                    logger.info("send msg for session--" + sess.getId());
                    sess.getBasicRemote().sendObject(rstJson);
                } else {
                    logger.info("discard msg for session--" + sess.getId());
                    sessionList.remove(sess);
                }
            }
        }
        // ssnMap.get (pushId).getBasicRemote ().sendObject (BeanAssemblyUtils.OK (rstJson));
    }
}
